package com.xianlai.microcosm_log

import android.os.Handler
import android.os.Looper
import androidx.annotation.NonNull
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import java.util.concurrent.atomic.AtomicBoolean

internal object ChannelManager : MethodChannel.MethodCallHandler {

    private var channel: MethodChannel? = null

    /**
     * flutter端是否初始化
     */
    val hasConnectFlutter: Boolean
        get() = hasConnected.get()

    private val hasConnected = AtomicBoolean(false)

    /**
     * flutter初始化后的回调
     */
    var connectFlutterListener: (() -> Unit)? = null

    /**
     * 切换与flutter通信时切换线程
     */
    private var handler: Handler? = null
    private var mainThread: Thread? = null

    fun init(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
        if (channel == null) {
            //多个FlutterEngine时，只处理第一个
            channel = MethodChannel(flutterPluginBinding.binaryMessenger, "microcosm_log")
            handler = Handler(Looper.getMainLooper())
            mainThread = Thread.currentThread()
        }

        channel?.setMethodCallHandler(this)
    }

    override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: MethodChannel.Result) {
        if (call.method == "onConnected") {
            //flutter初始化后，给android发信息
            if (hasConnected.compareAndSet(false, true)) {
                connectFlutterListener?.invoke()
            }
        } else {
            result.notImplemented()
        }
    }

    fun release() {
        hasConnected.set(false)
        channel?.setMethodCallHandler(null)
        //销毁时置空，恢复重新创建
        channel = null
    }

    fun sendMethodToFlutter(method: String, arguments: Any?) {
        //与flutter通信需要在主线程
        if (Thread.currentThread() == mainThread) {
            channel?.invokeMethod(method, arguments)
        } else {
            handler?.post {
                channel?.invokeMethod(method, arguments)
            }
        }
    }
}